﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data;
using System.Data.Common;

namespace Ice.ChinaKnowledge.Data
{
    public static class DataTransferTools
    {
        /// <summary>
        /// 将DataTable数据表转换为DataTransfer
        /// </summary>
        /// <param name="dataTable">DataTable</param>
        /// <returns>List<DataTransfer></returns>
        public static IEnumerable<DataTransfer> ArrayDataTransferWithDataTable(DataTable dataTable)
        {
            if (dataTable == null) throw new Exception("The object can not be empty.");

            foreach (DataRow dataRow in dataTable.Rows)
            {
                DataTransfer transfer = new DataTransfer();

                foreach (DataColumn column in dataTable.Columns)
                {
                    transfer.AddKeyValue(column.ColumnName, dataRow[column.ColumnName]);
                }

                yield return transfer;
            }
        }
        /// <summary>
        /// 将DataReader数据表转换为DataTransfer
        /// </summary>
        /// <param name="dataReader"></param>
        /// <returns></returns>
        public static IEnumerable<DataTransfer> ArrayDataTransferWithDataReader(IDataReader dataReader)
        {
            if (dataReader == null) throw new Exception("The object can not be empty.");

            while (dataReader.Read())
            {
                yield return new DataTransfer(dataReader);
            }
        }

        public static IEnumerable<T> ArrayEntityWithDataReader<T>(IDataReader dataReader)
        {
            if (dataReader == null) throw new Exception("The object can not be empty.");

            while (dataReader.Read())
            {
                var entity = EntityBuilder<T>.CreateInstance();

                (entity as DataTransfer).Fill(dataReader);

                yield return entity;
            }
        }
        public static T EntityWithDataTransfer<T>(DataTransfer dataTransfer)
        {
            var obj = EntityBuilder<T>.CreateInstance();

            (obj as DataTransfer).Fill(dataTransfer);

            return obj;
        }
      
    }
}
